<template>
  <div class="chat-container">
    <div class="message-area">
      <!-- 添加message-bubble类到消息容器 -->
      <div v-for="(msg, index) in messages" :key="index" class="message-bubble">
        <div class="message-meta">
          <span class="sender">{{ msg.sender }}</span>
          <span class="time">{{ new Date(msg.timestamp).toLocaleTimeString() }}</span>
        </div>
        <div class="message-content">{{ msg.content }}</div>
      </div>
    </div>

    <div class="input-area">
      <el-input v-model="message" @keydown.enter.native="sendMessage"></el-input>
      <el-button @click="sendMessage">发送</el-button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: '',
      ws: null,
      messages: [] // 新增消息存储数组
    }
  },
  mounted() {
    this.initWebSocket()
  },
  methods: {
    initWebSocket() {
      const token = JSON.parse(localStorage.getItem('user')).token
      this.ws = new WebSocket(`ws://localhost:8080/ws/chat?token=${token}`)

      this.ws.onopen = () => {
        console.log('WebSocket connected')
      }

      this.ws.onmessage = (event) => {
        console.log(event.data);
        const data = JSON.parse(event.data)
        console.log('Received message:', data)
        this.messages.push({
          sender: data.senderUsername,
          content: data.content,
          timestamp: data.createAt
        })

      }

      this.ws.onerror = (error) => {
        console.error('WebSocket error:', error)
      }

      this.ws.onclose = () => {
        console.log('WebSocket disconnected')
      }
    },
    sendMessage() {
      if (this.message.trim() && this.ws.readyState === WebSocket.OPEN) {
        const msgObj = {
          content: this.message,
          createAt: new Date().getTime(),
          type: 0
        }
        this.ws.send(JSON.stringify(msgObj))
        this.message = ''
      }
    }
  }
}
</script>

<style scoped>
@import url("../assets/css/views/chat-public.css");
</style>